package net.zigin.nhi.waste.view.rfid;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.siberiadante.titlelayoutlib.TitleBarLayout;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.BatchOutAdapter;
import net.zigin.nhi.waste.adapter.IActivityUpData;
import net.zigin.nhi.waste.adapter.IAnnounceTypeData;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.adapter.RfidBatchAdapter;
import net.zigin.nhi.waste.bean.BatchOutBean;
import net.zigin.nhi.waste.bean.RfidBatchBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.depotout.BatchOutActivity;
import net.zigin.nhi.waste.view.depotout.BatchOutCheckActivity;
import net.zigin.nhi.waste.view.depotout.BoxOutActivity;
import net.zigin.nhi.waste.view.depotout.BoxOutCheckActivity;
import net.zigin.nhi.waste.view.depotout.RfidOutActivity;
import net.zigin.nhi.waste.view.widget.BatchTypeDialog;
import net.zigin.nhi.waste.view.widget.GoBoxDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.paperdb.Paper;
import io.reactivex.Observable;

public class RfidBatchActivity extends AppCompatActivity {

    private TitleBarLayout mTitle;
    private RecyclerView mRvRfid;
    private ImageView mImg;
    private Button mDepot;
    private TextView mGo;

    private List<String> codes = new ArrayList<>();
    private List<RfidBatchBean> beanList = new ArrayList<>();
    private RfidBatchAdapter adapter;
    private NoDataAdapter noDataAdapter = new NoDataAdapter();
    private boolean isSelected = false;
    private List<String> wasteIDs = new ArrayList<>();
    private List<String> wasteTypes = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rfid_batch);
        initView();
        initListener();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mTitle = findViewById(R.id.title);
        mRvRfid = findViewById(R.id.rv_rfid);
        mImg = findViewById(R.id.img);
        mDepot = findViewById(R.id.depot);
        mGo = findViewById(R.id.go);

        mRvRfid.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initListener() {
        mTitle.setRightTextClickListener(v -> {
            BatchTypeDialog dialog = BatchTypeDialog.getInstance(this, RfidBatchActivity.this, typeDD);
            dialog.show();
        });

        mImg.setOnClickListener(v -> {
            if (isSelected) {
                isSelected = false;
                mImg.setImageResource(R.drawable.depot_in_unselected);

                for (RfidBatchBean bean : beanList) {
                    bean.setSelect(false);
                }
            } else {
                isSelected = true;
                mImg.setImageResource(R.drawable.depot_in_selected);

                for (RfidBatchBean bean : beanList) {
                    bean.setSelect(true);
                }
            }
            if (adapter != null) {
                adapter.notifyData(beanList);
            }

        });

        mDepot.setOnClickListener(v -> {
            wasteIDs.clear();
            wasteTypes.clear();
            JSONArray dtos = new JSONArray();
            Set<RfidBatchBean> newList = Paper.book().read(Constants.NEW_RFID_BATCH_LIST);
            if (newList != null && newList.size() > 0) {
                for (RfidBatchBean outBean : newList) {
                    if (outBean.isSelect()) {
                        JSONObject object = new JSONObject();
                        object.put("id", outBean.getId());
                        object.put("weight", outBean.getWeight());
                        dtos.add(object);

                        wasteIDs.add(outBean.getId());
                        wasteTypes.add(outBean.getWasteClassifyCode());
                    }
                }
                Paper.book().write(Constants.WASTE_BASE_IDS, wasteIDs);
            }
            if (wasteIDs.size() > 0) {
                if (StringUtil.removeDuplicate(wasteTypes).size() > 1) {
                    Toast.makeText(this, "只能选择同种类型的医废！", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(RfidBatchActivity.this, RfidOutActivity.class);
                    startActivity(intent);
                    finish();
                }
            } else {
                Toast.makeText(RfidBatchActivity.this, "请至少选中一项！", Toast.LENGTH_SHORT).show();
            }
        });

        mGo.setOnClickListener(v -> {
            GoBoxDialog dialog = new GoBoxDialog(this, RfidBatchActivity.this);
            dialog.show();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWasteDetail();
    }

    private void getWasteDetail() {
        codes.clear();
        Set<String> epcSet = Paper.book().read(Constants.EPCS);
        codes.addAll(epcSet);
        if (codes != null && codes.size() > 0) {
            beanList.clear();
            Map<String, Object> map = new HashMap<>();
            map.put("rfids", codes);
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getListByRfid(Paper.book().read(Constants.TOKEN), map);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @SuppressLint("DefaultLocale")
                @Override
                protected void success(String data) {
                    if (StringUtil.isNotEmpty(data)) {
                        Log.i("RFID医废详情", data);
                        JSONObject object = JSON.parseObject(data);
                        beanList = JSONArray.parseArray(object.getString("wasteBases"), RfidBatchBean.class);
                        if (beanList != null && beanList.size() > 0) {
                            adapter = new RfidBatchAdapter(beanList, dd);
                            mRvRfid.setAdapter(adapter);
                        } else {
                            mRvRfid.setAdapter(noDataAdapter);
                        }
                    } else {
                        mRvRfid.setAdapter(noDataAdapter);
                    }
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    mRvRfid.setAdapter(noDataAdapter);
                }
            });
        }

    }

    /**
     * 选择类型返回的数据更新adapter
     */
    private IAnnounceTypeData typeDD = new IAnnounceTypeData() {
        @Override
        public void upDataUi(String type) {
            if (StringUtil.isNotEmpty(type)) {
                if (type.equals("all")) {
                    isSelected = true;
                    mImg.setImageResource(R.drawable.depot_in_selected);

                    for (RfidBatchBean bean : beanList) {
                        bean.setSelect(true);
                    }
                    if (adapter != null) {
                        adapter.notifyData(beanList);
                    }
                } else {
                    if (beanList != null && beanList.size() > 0) {
                        for (RfidBatchBean batchOutBean : beanList) {
                            if (batchOutBean.getWasteClassifyCode().equals(type)) {
                                batchOutBean.setSelect(true);
                            } else {
                                batchOutBean.setSelect(false);
                            }
                        }
                        if (adapter != null) {
                            adapter.notifyData(beanList);
                        }
                    }
                }
            }
        }
    };

    /**
     * 子项取消选中时，全选按钮变更状态为未选中
     */
    private IActivityUpData dd = new IActivityUpData() {
        @Override
        public void upDataUi() {
            isSelected = false;
            mImg.setImageResource(R.drawable.depot_in_unselected);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BatchTypeDialog.mInstance = null;
    }
}